<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\model\admin\CateModel;
use app\model\admin\Pact;
use app\model\admin\ProductAttrTemp;
use think\facade\Validate;
use think\Request;

class ProductAttrTempController extends AdminBaseController
{
    // 获取
    public function index(Request $request)
    {
        $params = $request->param(['rule_name',  'created_at']);
        $list = ProductAttrTemp::scope('where', $params)->order('id', 'desc')->paginate([
            'list_rows' => $this->limit,
            'page' => $this->page,
            'var_page' => $this->pageVar
        ]);
        $arr = $list->items();

        foreach ($arr as $key => &$val) {
            $newValue = $val['rule_value'];
            $val['attr_name'] = implode(',', array_column($newValue, 'value'));
            $val['spec'] = $newValue;
            $attr_detail = array_column($newValue, 'detail');
            $attr_value = [];
            foreach ($attr_detail as $key => $val2) {
                $str = implode(',', $val2);
                array_push($attr_value, $str);
            }
            $val['attr_value'] = $attr_value;
        }

        return success([
            'items' => $arr,
            'pageSize' => $list->listRows(),
            'pageNum' => $list->currentPage(),
            'total' => $list->total(),
            'totalPage' => $list->lastPage(),
        ]);
        // return successPage($list);
    }
    // 获取
    public function getAll(Request $request)
    {
        $list = ProductAttrTemp::select();
        return success($list);
    }
    public function create(Request $request)
    {
        $validate = Validate::rule([
            "rule_name" => "require",
            "rule_value" => "require",
        ]);
        $params = $request->param(['rule_name', 'rule_value']);
        // 检验参数
        if (!$validate->check($params)) {
            return error($validate->getError());
        }
        $res = ProductAttrTemp::create($params);

        return success($res);
    }
    public function update(Request $request, $id)
    {
        $validate = Validate::rule([
            "rule_name" => "require",
            "rule_value" => "require",
        ]);
        $params = $request->param(['rule_name', 'rule_value']);
        // 检验参数
        if (!$validate->check($params)) {
            return error($validate->getError());
        }
        ProductAttrTemp::update($params, ["id" => $id]);
        return success();
    }
    public function del(Request $request, $id)
    {
        ProductAttrTemp::destroy($id);
        return success();
    }
}
